package org.easy.core.util;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;


public class FileUtil {
    private static final String TMP_DIR = System.getProperty("java.io.tmpdir");

    /**
     * 字符常量：斜杠 {@code '/'}
     */
    public static final char SLASH = '/';

    /**
     * 字符常量：反斜杠 {@code '\\'}
     */
    public static final char BACKSLASH = '\\';

    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";


    public static String getUUIDFilePath() {
        return TMP_DIR + "java" + UUID.randomUUID().toString().replace("-", "") + File.separator;
    }


    /**
     * 转文件大小到B
     *
     * @param size 1MB  2KB
     * @return
     */
    public static long parseSize(String size) {
        size = size.toUpperCase();
        long l = Long.parseLong(size.substring(0, size.length() - 2));
        return size.endsWith("KB") ? l * 1024L : (size.endsWith("MB") ? l * 1024L * 1024L : Long.parseLong(size));
    }

    /**
     * 获取文件后缀名
     *
     * @param originalFilename
     * @return
     */
    public static String getSuffixName(String originalFilename) {
        return originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
    }

    /**
     * 获取网络文件流
     *
     * @param url
     * @return
     */
    public static InputStream getUrlFileStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return connection.getInputStream();
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] toByteArray(InputStream is) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            byte[] b = new byte[4096];
            int n;
            while ((n = is.read(b)) != -1) {
                output.write(b, 0, n);
            }
            return output.toByteArray();
        } finally {
            output.close();
        }
    }


    /**
     * 创建文件
     * 如果目录不存在，则先创建目录
     *
     * @param fileName
     */
    public static void createFile(String fileName) {
        File file = new File(fileName);
        //文件存在则退出
        if (file.exists()) {
            return;
        }

        //文件是目录，直接创建
        if (fileName.endsWith(File.separator)) {
            file.mkdirs();
            return;
        }

        //非目录的情况  父目录不在则先创建
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            file.mkdirs();
        }

        //文件不存在，且父目录已存在后，执行创建新文件
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 级联删除目录
     *
     * @param dirs
     * @return
     */
    public static boolean deleteDirs(File dirs) {
        safeDeleteCheck(dirs);
        if (dirs.isDirectory()) {
            String[] children = dirs.list();
            //递归删除目录中的子目录下
            for (int i = 0; Objects.requireNonNull(children).length > i; i++) {
                boolean success = deleteDirs(new File(dirs, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dirs.delete();
    }

    private static final String[] SAFE_PATH = new String[]{"C:", "C:\\", "D:", "D:\\", "E:", "E:\\", "/", "~"};

    /**
     * 安全删除校验
     *
     * @param file
     */
    private static void safeDeleteCheck(File file) {
        if (Arrays.asList(SAFE_PATH).contains(file.getPath())) {
            throw new RuntimeException("根目录无法删除");
        }
    }

    /**
     * 合法化路径，使末尾一定包含分割符
     *
     * @param path 路径
     */
    public static String qualifyPath(String path) {
        if (!"".equals(path) && !path.endsWith(File.separator)) {
            path += File.separator;
        }
        return path;
    }

    /**
     * 获得系统路径
     *
     * @return
     */
    public static String getSystemPath() {
        if (System.getProperties().getProperty("os.name").contains("Windows")) {
            return "c:" + File.separator + "up3d" + File.separator;
        }
        return "/usr/tmp/up3d/";
    }

    /**
     * 输入流读到输出流
     * 并且关闭输入流
     *
     * @param inputStream
     * @param outputStream
     * @throws IOException
     */
    public static void outputStream(InputStream inputStream, OutputStream outputStream) throws IOException {
        try (InputStream in = inputStream) {
            final int maxSize = 2048;
            int readBytes;
            byte[] buffer = new byte[maxSize];
            while ((readBytes = in.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, readBytes);
            }
            outputStream.flush();
        }
    }


    public static void outputStream(byte[] bytes, OutputStream outputStream) throws IOException {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        outputStream(inputStream, outputStream);
    }

    /**
     * 文件写入本地
     *
     * @param url
     * @param path
     */
    public static boolean writeToLocal(String url, String path, String fileName) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        try (InputStream inputStream = FileUtil.getUrlFileStream(url);
             FileOutputStream fileOutputStream = new FileOutputStream(path + fileName)) {
            outputStream(inputStream, fileOutputStream);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 文件写入本地
     *
     * @param in
     * @param path
     */
    public static boolean writeToLocal(InputStream in, String path, String fileName) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        try (InputStream inputStream = in; FileOutputStream fileOutputStream = new FileOutputStream(path + fileName)) {
            outputStream(inputStream, fileOutputStream);
            return true;
        } catch (IOException ioException) {
            ioException.printStackTrace();
            return false;
        }
    }

    public static boolean writeFileToLocal(String url, String pathAndFileName) {
        File file = new File(pathAndFileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try (InputStream inputStream = FileUtil.getUrlFileStream(url);
             FileOutputStream fileOutputStream = new FileOutputStream(pathAndFileName)) {
            outputStream(inputStream, fileOutputStream);
            return true;
        } catch (IOException ioException) {
            ioException.printStackTrace();
            return false;
        }
    }


    public static boolean writeFileToLocal(InputStream in, String pathAndFileName) {
        File file = new File(pathAndFileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try (InputStream inputStream = in; FileOutputStream fileOutputStream = new FileOutputStream(pathAndFileName)) {
            outputStream(inputStream, fileOutputStream);
            return true;
        } catch (IOException ioException) {
            ioException.printStackTrace();
            return false;
        }
    }


    /**
     * 搜索目标文件
     *
     * @param searchStart
     * @param targetFile
     * @param levelLimit
     * @return
     */
    public static String searchFile(File searchStart, String targetFile, int levelLimit) {
        //超过指定层 中止搜索
        if (levelLimit < 0) {
            return null;
        } else {
            --levelLimit;
        }

        if (searchStart.isDirectory()) {
            for (File children : searchStart.listFiles()) {
                if (children.toString().endsWith(targetFile)) {
                    return children.toString();
                }
            }
            for (File children : searchStart.listFiles()) {
                if (!children.isDirectory()) {
                    continue;
                }
                String targetPath = searchFile(children, targetFile, levelLimit);
                if (targetPath != null) {
                    return targetPath;
                }
            }
        } else {
            if (searchStart.toString().endsWith(targetFile)) {
                return searchStart.toString();
            }
        }
        return null;
    }

    /**
     * 遍历子文件
     *
     * @param listStart
     * @param levelLimit
     * @param fileList
     */
    public static void listFile(File listStart, int levelLimit, List<File> fileList) {

        //超过指定层 中止搜索
        if (levelLimit < 0) {
            return;
        } else {
            --levelLimit;
        }


        if (listStart.isDirectory()) {

            for (File subFile : listStart.listFiles()) {
                listFile(subFile, levelLimit, fileList);
            }
        } else {
            fileList.add(listStart);
        }
    }

    /**
     * 行读文件
     *
     * @param path
     * @return
     */
    public static String readFileByLine(String path) {
        File file = new File(path);
        StringBuilder result = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            String s;
            while ((s = br.readLine()) != null) {
                result.append(s).append(System.lineSeparator());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }


    /**
     * 修改文件路径适配系统
     *
     * @param filePath
     * @return
     */
    public static String adepterSeparatorToFitFileSystem(String filePath) {
        return filePath.replace("/", File.separator).replace("\\", File.separator);
    }


    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 检查文件是否可下载
     *
     * @param resource 需要下载的文件
     * @return true 正常 false 非法
     */
    public static boolean checkAllowDownload(String resource) {
        // 禁止目录上跳级别
        if (StringUtils.contains(resource, "..")) {
            return false;
        }

        // 检查允许下载的文件规则
        return ArrayUtils.contains(MimeTypeUtil.DEFAULT_ALLOWED_EXTENSION, FileTypeUtil.getFileType(resource));

        // 不在允许下载的文件规则
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 返回文件名
     *
     * @param filePath 文件
     * @return 文件名
     */
    public static String getName(String filePath) {
        if (null == filePath) {
            return null;
        }
        int len = filePath.length();
        if (0 == len) {
            return filePath;
        }
        if (isFileSeparator(filePath.charAt(len - 1))) {
            // 以分隔符结尾的去掉结尾分隔符
            len--;
        }

        int begin = 0;
        char c;
        for (int i = len - 1; i > -1; i--) {
            c = filePath.charAt(i);
            if (isFileSeparator(c)) {
                // 查找最后一个路径分隔符（/或者\）
                begin = i + 1;
                break;
            }
        }

        return filePath.substring(begin, len);
    }

    /**
     * 是否为Windows或者Linux（Unix）文件分隔符<br>
     * Windows平台下分隔符为\，Linux（Unix）为/
     *
     * @param c 字符
     * @return 是否为Windows或者Linux（Unix）文件分隔符
     */
    public static boolean isFileSeparator(char c) {
        return SLASH == c || BACKSLASH == c;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", percentEncodedFileName);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }
}
